import { defineStore } from 'pinia'
import {
  getRolesAPI,
  getPermissionsAPI,
  getRolePermissionsAPI,
  updateRolePermissionsAPI,
  updateRoleStatusAPI,
  addRoleAPI
} from '@/apis/permissionAPI'

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    roles: [],
    permissions: [],
    selectedRole: null,
    rolePermissions: []
  }),

  actions: {
    // 获取角色列表
    async fetchRoles() {
      const res = await getRolesAPI()
      this.roles = res.data?.records || []
    },

    // 获取权限列表
    async fetchPermissions() {
      const res = await getPermissionsAPI()
      this.permissions = res.data?.records || []
    },

    // 获取角色权限
    async fetchRolePermissions(roleId) {
      const res = await getRolePermissionsAPI(roleId)
      this.rolePermissions = res.data?.records || []
      return this.rolePermissions
    },

    // 更新角色权限
    async updateRolePermissions({ roleId, permissionIds }) {
      await updateRolePermissionsAPI(roleId, permissionIds)
      await this.fetchRolePermissions(roleId)
    },

    // 更新角色状态
    async updateRoleStatus({ id, status }) {
      await updateRoleStatusAPI(id, status)
      await this.fetchRoles()
    },

    // 添加角色
    async addRole(roleData) {
      await addRoleAPI(roleData)
      await this.fetchRoles()
    },

    // 选择角色
    selectRole(role) {
      this.selectedRole = role
    }
  },

  getters: {
    // 角色状态样式
    roleStatusClass: () => (status) => {
      return status === 1
        ? 'bg-green-100 text-green-800'
        : 'bg-red-100 text-red-800'
    },

    // 检查权限是否已分配
    isPermissionAssigned: (state) => (permissionId) => {
      return state.rolePermissions.some(rp => rp.permissionId === permissionId)
    }
  }
})

// 选择角色
const selectRole = async (role) => {
  try {
    loading.value = true
    permissionStore.selectRole(role)
    await permissionStore.fetchRolePermissions(role.id)
    error.value = null
  } catch (err) {
    error.value = err.message || '加载角色权限失败'
    console.error('加载角色权限失败:', err)
  } finally {
    loading.value = false
  }
}

// 添加新角色
const addRole = async () => {
  if (!newRoleName.value.trim()) return

  try {
    loading.value = true
    await permissionStore.addRole({
      name: newRoleName.value,
      description: newRoleDesc.value,
      status: 1
    })
    // 重置表单
    newRoleName.value = ''
    newRoleDesc.value = ''
    showAddRoleForm.value = false // 隐藏表单
    error.value = null
  } catch (err) {
    error.value = err.message || '添加角色失败'
    console.error('添加角色失败:', err)
  } finally {
    loading.value = false
  }
}

// 保存权限分配
const savePermissions = async () => {
  try {
    loading.value = true
    const checkedPermissions = Array.from(
      document.querySelectorAll('input[type="checkbox"]:checked')
    ).map(el => parseInt(el.id.replace('permission-', '')))

    await permissionStore.updateRolePermissions({
      roleId: permissionStore.selectedRole.id,
      permissionIds: checkedPermissions
    })
    error.value = null
  } catch (err) {
    error.value = err.message || '保存权限失败'
    console.error('保存权限失败:', err)
  } finally {
    loading.value = false
  }
}

// 切换角色状态
const toggleRoleStatus = async (role) => {
  try {
    loading.value = true
    await permissionStore.updateRoleStatus({
      id: role.id,
      status: role.status === 1 ? 0 : 1
    })
    error.value = null
  } catch (err) {
    error.value = err.message || '更新角色状态失败'
    console.error('更新角色状态失败:', err)
  } finally {
    loading.value = false
  }
}
